package com.yrh.dao.impl;

import com.yrh.bean.TOrder;
import com.yrh.dao.TOrderDao;
import com.yrh.utils.DataSourceUtil;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;

/*订单数据层接口实现类*/
public class TOrderDaoImpl implements TOrderDao {
    private JdbcTemplate temp=new JdbcTemplate(DataSourceUtil.getDataSource());
    /*查询所有含分页*/
    @Override
    public List<TOrder> allOrder(TOrder tOrder,String userRole,int uid, int nowPage, int size) {
        String sql="SELECT t.*,u.user_name\n" +
                "FROM t_order t,t_user u\n" +
                "WHERE t.user_id=u.user_id";
        List<String> list=new ArrayList<>();
        if (userRole!=null&&!"".equals(userRole)&&"U".equals(userRole)){
            sql+=" and u.user_id=? ";
            list.add(uid+"");
        }
        if (tOrder.getAddTime()!=null&&!"".equals(tOrder.getAddTime())){
            sql += " and t.add_time  >= ?";
            list.add(tOrder.getAddTime());
        }
        if (tOrder.getUpdateTime()!=null&&!"".equals(tOrder.getUpdateTime())){
            sql += " and  update_time <= ? ";
            list.add(tOrder.getUpdateTime());
        }
        if (tOrder.getOrderType()!=0&&!"".equals(tOrder.getOrderType())){
            sql += " and  order_type = ? ";
            list.add(tOrder.getOrderType()+"");
        }
        if (tOrder.getOrderId()!=0&&!"".equals(tOrder.getOrderId())){
            sql += " and  order_id = ? ";
            list.add(tOrder.getOrderId()+"");
        }
        if (size!=0){
            sql+=" limit "+(nowPage-1)*size+","+size;
        }
        return temp.query(sql,list.toArray(),new BeanPropertyRowMapper<>(TOrder.class));
    }
    //修改订单状态
    @Override
    public int updateType(TOrder tOrder){
        return temp.update("update t_order set order_type=? where order_id=?",tOrder.getOrderType(),tOrder.getOrderId());
    }
    //生成订单
    @Override
    public int addOrder(TOrder order) {
        return temp.update("insert into t_order(update_time, user_id, address_details, order_type) values (now(),?,?,1)"
        ,order.getUserId(),order.getAddressDetails());
    }
    //查询最新订单
    @Override
    public int maxOrderId() {
        String sql="SELECT MAX(order_id) FROM t_order";
        return temp.queryForObject(sql,Integer.class);
    }

}
